import React, { useState } from 'react'
import PropTypes from 'prop-types'
import './style.scss'
import { useSelector, useDispatch } from 'react-redux'
// methods
import { calcCommentsCount } from '../../utils'
import { comment } from "../../pages/api"
// components
import { LOGOUT } from "../../store/action"
import { Comment, Form, Button, Divider, Input, Icon, Menu, Dropdown, message } from 'antd'
import List from './list' // 评论列表
import AppAvatar from '../Avatar'
import useBus from '../../hooks/useBus'

const { TextArea } = Input

const Editor = ({ onChange, onSubmit, submitting, value, articleId }) => (
  <div>
    <Form.Item>
      <TextArea rows={4} placeholder='说点什么...' onChange={onChange} value={value} />
    </Form.Item>
    <Form.Item>
      <div className='controls'>
        <Icon type='info-circle' className='controls-tip-icon' />
        <span className='controls-tip'>支持 Markdown 语法</span>
        <Button className='disscus-btn' htmlType='submit' loading={submitting} onClick={onSubmit} type='primary'>
          {articleId !== -1 ? '添加评论' : '留言'}
        </Button>
      </div>
    </Form.Item>
  </div>
)

function Discuss(props) {
  const dispatch = useDispatch()
  const bus = useBus()
  const userInfo = useSelector(state => state.userInfo)
  const { username } = userInfo

  const { commentList, articleId } = props
  const [value, setValue] = useState('')
  const [submitting, withLoading] = useState(false)
  const key = userInfo.userId + '_comment'


  const renderDropdownMenu = () => {
    return username ? (
      <Menu onClick={handleMenuClick}>
        <Menu.Item key='logout'>注销</Menu.Item>
      </Menu>
    ) : (
      <Menu onClick={handleMenuClick}>
        <Menu.Item key='login'>登录</Menu.Item>
        {/* <Menu.Item key='register'>注册</Menu.Item> */}
      </Menu>
    )
  }

  function handleMenuClick(e) {
    switch (e.key) {
      case 'login':
        bus.emit('openSignModal', '登录')
        break
      case 'register':
        //bus.emit('openSignModal', '注册')
        break
      case 'logout':
        dispatch(LOGOUT({ userId: userInfo.userId }))
        break
      default:
        break
    }
  }

  async function handleSubmit() {
    let time = localStorage.getItem(key) || 0
    if (!value) return message.warn('请输入内容！')
    if (time != 0) return message.warn(`请${time}秒后再评论！`)
    if (!userInfo.username) return message.warn('您未登陆，请登录后再试。')
    let res = await comment({ articleId: articleId, content: value, userId: userInfo.userId, username: userInfo.username })
    if (res.success) {
      localStorage.setItem(key, 30)
      loop()
      withLoading(true)
      setValue('')
      props.setCommentList(res.comments)
    }
  }

  function loop() {
    let time = Number(localStorage.getItem(key))
    let timeout = setTimeout(() => {
      if (time !== 0) {
          time--
          localStorage.setItem(key, time)
          loop()
      } else clearTimeout(timeout)
    }, 1000);
  }

  return (
    <div id='discuss'>
      <div className='discuss-header'>
        <span className='discuss-count'>{calcCommentsCount(commentList)}</span>
        {articleId !== -1 ? '条评论' : '条留言'}
        <span className='discuss-user'>
          <Dropdown overlay={renderDropdownMenu()} trigger={['click', 'hover']}>
            <span>
              {username || '未登录用户'} <Icon type='down' />
            </span>
          </Dropdown>
        </span>
        <Divider className='hr' />
      </div>

      <Comment
        avatar={
          username ? (
            <AppAvatar userInfo={userInfo} />
          ) : (
            <Icon type='github' theme='filled' style={{ fontSize: 40, margin: '5px 5px 0 0' }} />
          )
        }
        content={
          <Editor
            onChange={e => setValue(e.target.value)}
            onSubmit={handleSubmit}
            submitting={submitting}
            value={value}
            articleId={articleId}
          />
        }
      />

      <List commentList={commentList} articleId={articleId} setCommentList={props.setCommentList} />
    </div>
  )
}

Discuss.propTypes = {
  commentList: PropTypes.array.isRequired
}

export default Discuss
